/**
 * 
 */
package wpmp.security.mgr.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import wcommons.lang.NumberUtils;
import wpmp.extjs3.ExtjsUtils;
import wpmp.extjs3.data.Form;
import wpmp.extjs3.data.TreeNode;
import wpmp.security.mgr.Statics;
import wpmp.security.mgr.base.BaseAction;
import wpmp.security.mgr.base.DefaultBaseAction;
import wpmp.security.mgr.entity.Org;
import wpmp.security.mgr.service.OrgService;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 4:04:52 PM Mar 18, 2013
 */
@Action("org")
@Results({ @Result(name = BaseAction.LIST, location = "/WEB-INF/org/list.jsp"),
		@Result(name = BaseAction.INPUT, location = "/WEB-INF/org/input.jsp"),
		@Result(name = OrgAction.SELECT, location = "/WEB-INF/org/select.jsp") })
public class OrgAction extends DefaultBaseAction<Org> {

	private static final long serialVersionUID = 1L;

	private static final Logger LOG = LoggerFactory.getLogger(OrgAction.class);

	static final String SELECT = "select";

	@Autowired
	private OrgService service;

	public String list() throws Exception {
		this.getRequest().setAttribute("ROOT_NAME", service.getRootOrg().getName());
		return LIST;
	}

	public String select() throws Exception {
		this.getRequest().setAttribute("ROOT_NAME", service.getRootOrg().getName());
		return SELECT;
	}

	public String input() throws Exception {
		final HttpServletRequest req = this.getRequest();

		String parentName = null;
		Org parent = null;
		if (NumberUtils.gtZero(entity.getParentId())) {
			parent = service.get(entity.getParentId());
		}
		else if (NumberUtils.gtZero(entity.getId())) {
			parent = service.getParent(entity.getId());
		}
		if (parent != null) {
			parentName = parent.getName();
		}
		req.setAttribute("PARENT_NAME", StringUtils.trimToEmpty(parentName));

		return INPUT;
	}

	public void listJSON() throws Exception {
		final HttpServletRequest req = this.getRequest();

		Long id = entity.getId();
		if (!NumberUtils.gtZero(id)) {
			String node = req.getParameter("node");
			if (StringUtils.isNotBlank(node)) {
				id = Long.valueOf(node);
			}
		}
		if (!NumberUtils.gtZero(id)) {
			id = Statics.ROOT_ID;// root 节点
		}
		final SqlRowSet rs = service.queryChildrenIsLeaf(id);
		final List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		for (Org child : service.getChildren(id)) {
			final TreeNode treeNode = new TreeNode();
			treeNode.setId(child.getId().toString());
			treeNode.setText(child.getName());

			boolean isLeaf = true;
			while (rs.next()) {
				if (NumberUtils.eq(child.getId(), rs.getLong("id"))) {
					isLeaf = rs.getBoolean("is_leaf");
				}
			}
			rs.beforeFirst();
			treeNode.setLeaf(isLeaf);
			treeNode.addAttribute("orderNum", child.getOrderNum());
			treeNodes.add(treeNode);
		}

		this.renderJson(TreeNode.toJSONString(treeNodes));
	}

	public void getJSON() throws Exception {
		final Org result = service.get(entity.getId());

		if (LOG.isDebugEnabled()) {
			LOG.debug("{}", result);
		}

		if (result == null) {
			LOG.warn("can not found Org by id[{}]", entity.getId());

			this.renderJson(ExtjsUtils.getDefaultErrorFormJSONString(Statics.DEFAULT_ERROR_MSG));
			return;
		}

		final String jsonString = Form.newInstance(result).toJSONString();

		if (LOG.isDebugEnabled()) {
			LOG.debug(jsonString);
		}

		this.renderJson(jsonString);
	}

	public void insertJSON() throws Exception {
		this.renderJson(service.insert(entity).toJSONString());
	}

	public void updateJSON() throws Exception {
		this.renderJson(service.update(entity).toJSONString());
	}

	public void deleteJSON() throws Exception {
		this.renderJson(service.delete(entity.getId()).toJSONString());
	}

	public void sortJSON() throws Exception {
		this.renderJson(service.sort(entity).toJSONString());
	}

	@Override
	public Org getModel0() {
		if (entity == null) {
			entity = new Org();
		}
		return entity;
	}

}
